<template>
  <div class="box">
    <a-table
        :columns="columns"
        :dataSource="tableData"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        :scroll="{
        x: 'max-content',
      }"
        bordered
    >
      <template #title>
        <div>
          <a-row :wrap="true" :gutter="[9, 10]">
            <a-col
                :xl="$store.getters.isMobile ? 12 : 4"
                :lg="$store.getters.isMobile ? 12 : 6"
                :md="$store.getters.isMobile ? 12 : 8"
                :sm="12"
                :xs="$store.getters.isMobile ? 12 : 24"
            >
              <a-input
                  class="w-100"
                  v-model:value="name"
                  placeHolder="搜索联系人名称"
              ></a-input
              >
            </a-col>
            <a-col
                :xl="$store.getters.isMobile ? 12 : 4"
                :lg="$store.getters.isMobile ? 12 : 6"
                :md="$store.getters.isMobile ? 12 : 8"
                :sm="12"
                :xs="$store.getters.isMobile ? 12 : 24"
            >
              <a-input
                  class="w-100"
                  v-model:value="phone"
                  placeHolder="搜索联系人电话"
              ></a-input
              >
            </a-col>
            <a-col
                :xl="$store.getters.isMobile ? 12 : 4"
                :lg="$store.getters.isMobile ? 12 : 6"
                :md="$store.getters.isMobile ? 12 : 8"
                :sm="12"
                :xs="$store.getters.isMobile ? 12 : 24"
            >
              <a-select
                  class="w-100"
                  placeholder="选择渠道"
                  :options="sourceOptions"
                  v-model:value="source"
              >
              </a-select>
            </a-col>
            <a-col>
              <div>
                <a-button style="margin-right: 10px" @click="reset"
                >重置
                </a-button>
                <a-button type="primary" @click="toSearch">搜索</a-button>
              </div>
            </a-col>

            <a-col style="margin-left: auto">
              <a-button type="primary" @click="addChannel">+新增渠道</a-button>
            </a-col>
          </a-row>
        </div>
      </template>

      <template #bodyCell="{ column, record }">
        <template
            v-if="
            column.key == 'name' ||
            column.key == 'phone' ||
            column.key == 'village_name' ||
            column.key == 'created_at'
          "
        >
          {{ record[column.key] }}
        </template>

        <template v-if="column.key == 'clueNum'">
          <a-button type="link" @click="showClueList(record.id)">{{
              record.clue_number
            }}
          </a-button>
        </template>
        <template v-if="column.key == 'userNum'">
          <a-button type="link" @click="showUserList(record.id)">{{
              record.customer_number
            }}
          </a-button>
        </template>

        <template v-if="column.key == 'contract_number'">
          <a-button type="link" @click="toContractInfo(record.id)">{{
              record.contract_number
            }}
          </a-button>
        </template>
        <template v-if="column.key == 'source'">
          {{ record[column.key]?.source || "--" }}
        </template>

        <template v-if="column.key == 'template'">
          <a-space>
            <span>
              {{ record?.template?.name || "--" }}
            </span>
            <a-button type="link" @click.stop="selectTemplateInfo(record)">
              <FormOutlined/>
            </a-button>
          </a-space>
        </template>

        <template v-if="column.key == 'action'">
          <!-- <a-button type="link" @click="toContractInfo(record.id)"
            >成交合同</a-button
          > -->
          <a-button type="link" @click="editChannel(record.id)">编辑</a-button>
          <a-button type="link" @click="toBlacklist(record.id)" danger
          >加入黑名单
          </a-button
          >
          <a-popconfirm
              title="确认删除该渠道信息? "
              ok-text="确认"
              cancel-text="取消"
              @confirm="deleteChanel(record.id)"
          >
            <a-button type="link" danger>删除</a-button>
          </a-popconfirm>
        </template>
      </template>
    </a-table>

    <!-- 加入黑名单弹窗 -->
    <a-modal
        v-model:visible="blackVisible"
        title="加入黑名单"
        centered
    >
      <div style="padding: 10px">
        <div style="font-size: 18px; font-weight: 500; color: #333">
          确定要将该渠道加入黑名单嘛？
        </div>
        <div style="margin: 10px 0; font-size: 12px">
          <a-checkbox v-model:checked="blackChecked">设置黑名单时间</a-checkbox>
        </div>
        <div v-if="blackChecked">
          <a-date-picker
              style="width: 100%"
              v-model:value="blacklist_time"
              :valueFormat="dateFormatStr"
          ></a-date-picker>
        </div>
        <div style="font-size: 11px; color: #666; margin: 10px 0">
          当时间大于黑名单时间后，则渠道自动解除黑名单限制
        </div>
      </div>
      <template #footer>
        <a-row style="width: 100%;" justify="end">
          <a-col>
            <a-space>
              <a-button @click="cancelSet">取消</a-button>
              <a-button type="primary" @click="commitBlacklist">确定</a-button>
            </a-space>
          </a-col>
        </a-row>
      </template>
    </a-modal>

    <!-- 新增  、编辑-->
    <ChannelManagemntEdit
        :visible="visible"
        @cancel="btnCancel"
        :optionsBuild="optionsBuild"
        :id="editID"
        @btnOk="submitSucc"
    />

    <!-- 线索列表 -->
    <CheckClueDetail
        :visible="showClue"
        :id="detailID"
        @closeDetail="closeDetail"
    />

    <!-- 客户列表 -->
    <CheckUserDetail
        :visible="showUser"
        :id="detailID"
        @closeDetail="closeUserDetail"
        :isChannel="1"
    />

    <!-- 详情、、、成交合同 -->
    <ChannelDetail
        :visible="detailVisible"
        :id="detailID"
        @closeDrawer="hideDrawer"
    />

    <!--  设置佣金模板  -->
    <SetCommissionTemplate
        :from="1"
        :visible="editTemplateVisible"
        :id="detailID"
        :templateId="templateId"
        @handleCancel="editTemplateVisible = false"
        @success="handleTemplateSuccess"
    />
  </div>
</template>

<script>
import {ref, reactive, toRefs, watch, computed} from "vue";
import request from "../../../../common/utils/request";
import {message} from "ant-design-vue";
import {FormOutlined} from "@ant-design/icons-vue";
import ChannelManagemntEdit from "./ChannelManagemntEdit.vue";
import ChannelDetail from "./ChannelDetail.vue";
import CheckClueDetail from "./CheckClueDetail.vue";
import CheckUserDetail from "./CheckUserDetail.vue";
import SetCommissionTemplate from "./SetCommissionTemplate.vue";

const dateFormatStr = "YYYY-MM-DD";
export default {
  props: {
    activeKey: {
      type: String,
      default: "",
    },
    sourceOptions: {
      type: Array,
      default: () => [],
    },
    optionsBuild: {
      type: Array,
      default: () => [],
    },
  },
  components: {
    ChannelManagemntEdit,
    FormOutlined,
    ChannelDetail,
    CheckClueDetail,
    CheckUserDetail,
    SetCommissionTemplate,
  },
  setup(props, context) {
    const state = reactive({
      loading: false,
      templateId: 0,
    });

    const blackVal = reactive({
      blackVisible: false,
      blackChecked: false,
      id: 0,
      blacklist_time: undefined,
    });

    const columns = [
      {title: "联系人名称", key: "name"},
      {title: "联系人电话", key: "phone"},
      {title: "所在区域", key: "address", dataIndex: "address"},
      {title: "线索数量", key: "clueNum"},
      {title: "意向客户数量", key: "userNum"},
      {title: "成交合同数", key: "contract_number"},
      {title: "佣金模板", key: "template"},
      {title: "渠道类型", key: "source"},
      {title: "来源", key: "causation_txt", dataIndex: "causation_txt"},
      {title: "关联项目", key: "village_name"},
      {title: "创建时间", key: "created_at"},
      {
        title: "操作",
        key: "action",
        width: "15%",
      },
    ];

    const searchParam = reactive({
      name: "",
      phone: "",
      source: undefined,
    });

    const total = ref(0);
    const page = ref(1);
    const limit = ref(10);
    const pagination = computed(() => ({
      total: total.value,
      current: page.value,
      pageSize: limit.value,
      showSizeChanger: true,
    }));

    const tableData = ref([]);
    const getTableData = () => {
      state.loading = true;
      const param = {type: 1, page: page.value, pageSize: limit.value};
      Object.keys(searchParam).forEach((key) => {
        if (searchParam[key]) {
          param[key] = searchParam[key];
        }
      });
      request
          .get("/org", "/business/customer/channel", param)
          .then((res) => {
            console.log(res);
            tableData.value = res.list;
            total.value = res.total;
            context.emit("numChange", res.customerStatus0Count + res.waitAuditCompanyCount);

          })
          .finally(() => {
            state.loading = false;
          });
    };

    const handleTableChange = (pager, filters, sorter) => {
      console.log(pager);
      page.value = pager.current;
      limit.value = pager.pageSize;
      getTableData();
    };

    const btnCancel = () => {
      visible.value = false;
    };

    // 合同  详情
    const detailID = ref(0);
    const detailVisible = ref(false);
    const toContractInfo = (val) => {
      detailID.value = val;
      detailVisible.value = true;
    };
    const hideDrawer = () => {
      detailVisible.value = false;
    };

    //黑名单
    const toBlacklist = (val) => {
      blackVal.blackVisible = true;
      blackVal.id = val;
    };

    const cancelSet = () => {
      blackVal.blackVisible = false;
    };
    const commitBlacklist = () => {
      console.log(blackVal);
      if (blackVal.blackChecked && !blackVal.blacklist_time) {
        message.error("请选择黑名单时间！");
        return;
      }
      const param = {
        id: blackVal.id,
      };
      if (blackVal.blacklist_time) {
        param.blacklist_time = blackVal.blacklist_time;
      }

      request
          .post("/org", "/business/customer/channel/addBlack", param)
          .then((res) => {
            message.success("操作成功");
            blackVal.blackVisible = false;
            blackVal.blackChecked = false;
            blackVal.blacklist_time = undefined;
            getTableData();
          });
    };

    const reset = () => {
      Object.keys(searchParam).forEach((key) => {
        searchParam[key] = key == "source" ? undefined : "";
      });
      page.value = 1;
      getTableData();
    };

    const toSearch = () => {
      page.value = 1;
      getTableData();
    };
    const visible = ref(false);
    // 新增渠道
    const addChannel = () => {
      editID.value = 0;
      visible.value = true;
    };

    // 编辑
    const editID = ref();
    const editChannel = (val) => {
      editID.value = val;
      visible.value = true;
    };

    const submitSucc = () => {
      visible.value = false;
      getTableData();
    };

    // 删除
    const deleteChanel = (val) => {
      console.log(val);
      request
          .del("/org", "/business/customer/channel", {id: val})
          .then((res) => {
            console.log(res);
            message.success("删除成功！");
            getTableData();
          });
    };

    // 线索相关
    const showClue = ref(false);
    const showClueList = (val) => {
      detailID.value = val;
      showClue.value = true;
    };

    const closeDetail = () => {
      showClue.value = false;
    };

    // 客户相关
    const showUser = ref(false);
    const showUserList = (val) => {
      detailID.value = val;
      showUser.value = true;
    };
    const closeUserDetail = () => {
      showUser.value = false;
    };

    const editTemplateVisible = ref(false);
    const selectTemplateInfo = (item) => {
      console.log(item);
      state.templateId = item.template_id || 0;
      detailID.value = item.id;
      editTemplateVisible.value = true;
    };

    const handleTemplateSuccess = () => {
      editTemplateVisible.value = false;
      page.value = 1;
      getTableData();
    };

    watch(
        () => props.activeKey,
        (val) => {
          if (val == "info") getTableData();
        },
        {
          immediate: true,
        }
    );

    return {
      ...toRefs(state),
      ...toRefs(blackVal),
      ...toRefs(searchParam),
      columns,
      tableData,
      pagination,
      handleTableChange,
      toBlacklist,
      toContractInfo,
      deleteChanel,
      cancelSet,
      commitBlacklist,
      reset,
      toSearch,
      addChannel,
      btnCancel,
      visible,
      submitSucc,
      editChannel,
      editID,
      detailID,
      detailVisible,
      hideDrawer,
      showClueList,
      showUserList,
      showClue,
      showUser,
      closeDetail,
      closeUserDetail,
      selectTemplateInfo,
      editTemplateVisible,
      handleTemplateSuccess,
      dateFormatStr,
    };
  },
};
</script>

<style lang="less" scoped>
.box {
  padding: 10px;
}

.info-title {
  display: flex;
  justify-content: space-between;
}

.w-100 {
  width: 100%;
}

.mobile-box {
  .mobile-item {
    width: 100%;
  }
}
</style>
